package org.leetcode.middle.leetcode146;

import java.awt.event.KeyEvent;
import java.util.HashMap;

public class LRUCache5 {
    public class Node {
        int key;
        int val;
        Node next;
        Node pre;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    int size;
    Node dummy;

    public LRUCache5(int size) {
        this.size = size;
        dummy = new Node(-1, -1);
        dummy.next = dummy;
        dummy.pre = dummy;
    }

    HashMap<Integer,Node> hashMap = new HashMap<>();


    public void put(int key,int val){
        Node node = getNode(key);
        if (node!=null){
            node.val = val;
        }else {
            Node newNode = new Node(key,val);
            hashMap.put(key,newNode);
            putNodeFirst(key);
            if (hashMap.size()>size){
                hashMap.remove(dummy.pre.key);
                removeNode(dummy.pre);
            }
        }
    }
    public int get(int key){
        Node node = getNode(key);
        if (node==null){
            return -1;
        }
        return node.val;
    }


    private Node getNode(int key){
        if (!hashMap.containsKey(key)){
            return null;
        }else {
            Node node = hashMap.get(key);
            removeNode(node);
            putNodeFirst(key);
            return node;
        }
    }

    private void putNodeFirst(int key){
        Node node = hashMap.get(key);

        dummy.next.pre=node;
        node.next=dummy.next;
        dummy.next=node;
        node.pre=dummy;
    }

    private void removeNode(Node node){
        node.pre.next=node.next;
        node.next.pre = node.pre;
    }
}
